package com.ophiux.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * 说明：http请求<br>
 * <h1>创 建 人: hehailong   <br></h1>
 * 创建日期: 2017-9-19 上午11:11:22<br>
 * 需要的jar包:getPostMethodSSL()方法  依赖commons-logging-1.0.3.jar，httpclient-4.3.5.jar，httpcore-4.3.2.jar
 */
public class HttpUtil {
	private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
	public static String HTTP_POST = "POST";
	public static String HTTP_GET = "GET";
	
	/**
	 * 
	 * @param requestUrl  
	 * @param requestMethod  
	 * @param outputStr  
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl,String requestMethod,
			String outputStr) throws Exception{
		return httpsRequest(requestUrl, requestMethod, outputStr, 30*1000);
	}
	
	/**
	 * 
	@param requestUrl  请求地址
	 * @param requestMethod 	请求方式
	 * @param outputStr  
	 * @param timeout   超时时间
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl,String requestMethod,
							String outputStr,int timeout) throws Exception{
		
//		StringBuffer buffer = null;
//		try {
//			URL url = new URL(requestUrl);
//			
//			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
//			conn.setRequestMethod(requestMethod);
//			conn.setDoInput(true);
//			conn.setDoOutput(true);
//			conn.setConnectTimeout(timeout);
//			conn.connect();
//			if(outputStr != null){
//				OutputStream os = conn.getOutputStream();
//				os.write(outputStr.getBytes("utf-8"));
//				os.close();
//			}
//			
//			InputStream is = conn.getInputStream();
//			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
//			BufferedReader br = new BufferedReader(isr);
//			
//		    buffer = new StringBuffer(); 
//			String line = null;
//			
//			while((line = br.readLine())!=null){
//				buffer.append(line);
//			}
//			
//		} catch (Exception e) {
//			throw e;
//		}
//		return buffer.toString();
		
		
		
        URL httpUrl = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setRequestProperty("Host", "https://api.mch.weixin.qq.com");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setConnectTimeout(10*1000);
        httpURLConnection.setReadTimeout(10*1000);
        httpURLConnection.connect();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(outputStr.getBytes("UTF-8"));

        //获取内容
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        final StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String resp = stringBuffer.toString();
        if (stringBuffer!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream!=null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return resp;
	}
	

	public static String getPostMethodSSL(String serviceURL, String methodName,
			String strParam, String sslFilePath, String mch_id) throws Exception{
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(new File(sslFilePath));
		String jsonStr = "";
		CloseableHttpResponse response = null;
		try {
			keyStore.load(instream, mch_id.toCharArray());
		} finally {
			instream.close();
		}
		SSLContext sslcontext = SSLContexts.custom()
				.loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try {
			HttpPost httpost = new HttpPost(serviceURL);
			System.out.println("executing request" + httpost.getRequestLine());
			try {
				httpost.addHeader("Connection", "keep-alive");
				httpost.addHeader("Accept", "*/*");
				httpost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
				httpost.addHeader("Host", "api.mch.weixin.qq.com");
				httpost.addHeader("X-Requested-With", "XMLHttpRequest");
				httpost.addHeader("Cache-Control", "max-age=0");
				httpost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
				httpost.setEntity(new StringEntity(strParam, "UTF-8"));
				response = httpclient.execute(httpost);
				HttpEntity entity = response.getEntity();
				jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return jsonStr;
	}
	
	
	public static String post(final String url, final String param) {
	    Callable callable = new Callable<String>() {
	        public String call() throws Exception {
	          return HttpUtil.sendPost(url, param);
	        }
	      };
	    Future<String> temp = fixedThreadPool.submit(callable);
	    try {
	      return temp.get();
	    }
	    catch(Exception e) {
	    	e.printStackTrace();
	    }
	    return null;
	  }
	
	
	public static String sendPost(String url, String param) {
	    PrintWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	    try {
	      URL realUrl = new URL(url);
	      // 打开和URL之间的连接
	      URLConnection conn = realUrl.openConnection();
	      // 设置通用的请求属性
	      conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
	      // 发送POST请求必须设置如下两行
	      conn.setDoOutput(true);
	      conn.setDoInput(true);
	      // 获取URLConnection对象对应的输出流
	      OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
	      out = new PrintWriter(outWriter);
	      // 发送请求参数
	      out.print(param);
	      // flush输出流的缓冲
	      out.flush();
	      // 定义BufferedReader输入流来读取URL的响应
	      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	      String line;
	      while((line = in.readLine()) != null) {
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        result += line;
	      }
	    }
	    catch(Exception e) {
	      System.out.println("发送 POST 请求出现异常！" + e);
	      e.printStackTrace();
	    }
	    // 使用finally块来关闭输出流、输入流
	    finally {
	      try {
	        if(out != null) {
	          out.close();
	        }
	        if(in != null) {
	          in.close();
	        }
	      }
	      catch(IOException ex) {
	        ex.printStackTrace();
	      }
	    }
	    return result;
	  }
}
